<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="员工姓名">
                <a-input
                  v-model="queryParam.staffName"
                  placeholder="请输入员工姓名" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="部门">
                <a-input
                  v-model="queryParam.department"
                  placeholder="请输入部门" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="16">
              <a-form-item label="岗位">
                <a-input
                  v-model="queryParam.jobs"
                  placeholder="请输入岗位" />
              </a-form-item>
            </a-col>
            <a-col
              :md="6"
              :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button
                  type="primary"
                  v-if="list"
                  @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  v-if="list"
                  @click="() => {this.queryParam = {};this.$refs.table.refresh() }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button
          type="primary"
          icon="plus"
          v-if="save"
          @click="handleAdd">新建</a-button>
      </div>
      <div>
        <a-row :gutter="48">
          <a-spin :spinning="confirmLoading">
            <a-col
              :md="24"
              :sm="24">
              <s-table
                ref="table"
                size="default"
                rowKey="rewardId"
                :columns="columns"
                :data="loadData"
                :customRow="tableCustomRow"
                showPagination="auto">
                <span
                  slot="serial"
                  slot-scope="text, record, index">
                  {{ index + 1 }}
                </span>
                <span
                  slot="validTime"
                  slot-scope="text, record">
                  {{ record.validBeginDate.split(' ')[0] }} ~ {{ record.validEndDate.split(' ')[0] }}
                </span>
                <span
                  slot="execDate"
                  slot-scope="text, record">
                  {{ record.execDate.split(' ')[0] }}
                </span>
                <span
                  slot="createTime"
                  slot-scope="text, record">
                  {{ record.createTime.split(' ')[0] }}
                </span>
                <span
                  slot="action"
                  slot-scope="text, record">
                  <template>
                    <a v-if="update" @click="handleEdit(record)">配置</a>
                    <a-divider type="vertical" />
                    <a v-if="deleteBtn" @click="handleDelete(record)">删除</a>
                  </template>
                </span>
              </s-table>
            </a-col>
          </a-spin>
        </a-row>
      </div>
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :allUsers="allUsers"
        @cancel="handleCancel"
        @ok="handleOk" />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import { getRewardList, allStaff, deleteRewardReq, saveReward, updateReward } from '@/api/manage'
import CreateForm from './modules/CreateForm'
import { columns } from './config'
import { isInMenu } from '../config.js'
import { mapGetters } from 'vuex'

import { Modal } from 'ant-design-vue'
export default {
  name: 'TableList',
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
                 // 权限参数
      list: false, // 列表
      save: false, // 加
      deleteBtn: false, // 删
      update: false, // 改

      // create model
      visible: false,
      confirmLoading: false,
      reward: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      add: false,
      edit: false,
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      physicalSurveyCurrRowId: null,
      allUsers: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = { page: parameter.pageNo, limit: parameter.pageSize }
        const param = Object.assign({}, this.queryParam)
        return this.list && getRewardList(Object.assign({}, param, requestParameters)).then(res => {
          return Object.assign({}, res, {
            totalCount: res.total,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize
          })
        })
      }
    }
  },
  filters: {},
  created () {
        // 点击查看
    this.list = isInMenu(this.menu, 'ROLE_but:reward:list') && isInMenu(this.menu, 'ROLE_but:reward:info')
    // 增加
    this.save = isInMenu(this.menu, 'ROLE_but:reward:save') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 改
    this.update = isInMenu(this.menu, 'ROLE_but:reward:update') && isInMenu(this.menu, 'ROLE_but:user:select')
    // 删除
    this.deleteBtn = isInMenu(this.menu, 'ROLE_but:reward:delete')
  },
  mounted () {
    isInMenu(this.menu, 'ROLE_but:user:select') && allStaff().then(res => {
      this.allUsers = res.data
    })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd () {
      // this.mdl = null
      this.visible = true
      this.add = true
      this.edit = false
    },
    handleDelete (record) {
      Modal.confirm({
        title: '删除奖惩信息',
        content: '删除后数据不再展示，需要查看请联系开发',
        onOk: () => {
          this.confirmLoading = true
          deleteRewardReq({ rewardId: record.rewardId })
            .then(res => {
              this.$message.success('删除成功')
              this.$refs.table.refresh()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleEdit (record) {
      this.visible = true
      this.reward = record
      this.add = false
      this.edit = true
      const form = this.$refs.createModal.form
      this.$nextTick(() => {
        form.setFieldsValue(
          Object.assign(
            {},
            {
              staffId: this.reward.staffId,
              execDate: this.reward?.execDate,
              type: this.reward.type,
              execResult: this.reward.execResult,
              note: this.reward.note,
              deed: this.reward.deed,
              status: this.reward.status,
              validDate: [this.reward.validBeginDate, this.reward.validEndDate]
            }
          )
        )
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.add) {
            this.confirmLoading = true
            saveReward(
              Object.assign({}, values, {
                validDate: undefined,
                validBeginDate: values.validDate[0],
                validEndDate: values.validDate[1]
              })
            )
              .then(res => {
                if (res.code === 0) {
                  this.add = false
                  form.resetFields()
                  this.$refs.table.refresh()
                  this.confirmLoading = false
                  this.$message.success('新增成功')
                }
              })
              .finally(() => {
                this.visible = false
              })
          } else if (this.edit) {
            this.confirmLoading = true
            updateReward(
              Object.assign({}, values, {
                validDate: undefined,
                validBeginDate: values.validDate[0],
                validEndDate: values.validDate[1],
                execDate: values.execDate,
                rewardId: this.reward.rewardId
              })
            )
              .then(res => {
                if (res.code === 0) {
                  this.edit = false
                  form.resetFields()
                  this.$refs.table.refresh()
                  this.confirmLoading = false
                  this.visible = false
                  this.$message.success('配置成功')
                }
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    },
    tableCustomRow (record, index) {
      return {
        style: {
          'background-color': record.rewardId === this.physicalSurveyCurrRowId ? '#dff3fe' : 'white'
        },
        on: {
          click: event => {
            this.physicalSurveyCurrRowId = record.rewardId
            // this.staffInfo = record
          }
        }
      }
    }
  }
}
</script>
